package com.first.nell.repay

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.first.nell.R
import com.first.nell.base.*
import com.first.nell.data.ReqBase
import com.first.nell.data.ReqRepayUrl
import com.first.nell.databinding.FragmentFirstNellRepayOverrollerBinding
import com.first.nell.enums.PageTagEnum
import com.first.nell.extend.*
import com.first.nell.launch.UserStateViewModel
import com.first.nell.utils.InfoProcessUtil
import com.first.nell.utils.UsageCountryUtil

/** 还款页 */
class RepayFragment : BaseFragment() {

    //布局binding
    private lateinit var mFirstNellFragmentFirstNellBinding: FragmentFirstNellRepayOverrollerBinding

    //用户流程viewModel
    private val mUserStateViewModel by lazy {
        ViewModelProvider(this)[UserStateViewModel::class.java]
    }

    //还款viewModel
    private val mRepayViewModel by lazy {
        ViewModelProvider(this)[RepayViewModel::class.java]
    }

    override fun onFirstNellBindingFirstNellViewFirstNellModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mUserStateViewModel)
        list.add(mRepayViewModel)
        return list
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        mFirstNellFragmentFirstNellBinding =
            FragmentFirstNellRepayOverrollerBinding.inflate(inflater, container, false)
        return mFirstNellFragmentFirstNellBinding.root
    }

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        try {
            //初始化下拉刷新
            activity?.let { curActivity ->
                mFirstNellFragmentFirstNellBinding.srlRepayPullRefresh.apply {
                    setColorSchemeColors(
                        ContextCompat.getColor(
                            curActivity,
                            R.color.main_blue
                        )
                    )

                    setOnRefreshListener {
                        val reqBase = ReqBase()
                        reqBase.showLoading = false
                        mUserStateViewModel.fetchFirstNellUserFirstNellState(reqBase)
                    }
                }
            }

            //获取用户状态回调
            mUserStateViewModel.onFirstNellFetchFirstNellUserFirstNellStateFirstNellLiveData.observe(
                viewLifecycleOwner
            ) {
                mFirstNellFragmentFirstNellBinding.srlRepayPullRefresh.isRefreshing = false
                if (it.isSuccess) {
                    try {
                        if (InfoProcessUtil.isFirstNellRepayFirstNellNow()) {
                            //获取还款信息
                            val reqBase = ReqBase()
                            reqBase.showLoading = false
                            mRepayViewModel.fetchFirstNellRepayFirstNellDetail(reqBase)
                        } else {
                            //下一步
                            startFirstNellToFirstNellNextFirstNellFromFirstNellPage(PageTagEnum.repay)
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }

            //获取还款信息回调
            mRepayViewModel.onFirstNellFetchFirstNellRepayFirstNellDetailFirstNellLiveData.observe(
                viewLifecycleOwner
            ) {
                mFirstNellFragmentFirstNellBinding.srlRepayPullRefresh.isRefreshing = false
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        //保存还款信息
                        mRepayViewModel.mFirstNellRepayFirstNellInfo = result

                        //还款金额
                        mFirstNellFragmentFirstNellBinding.textRepayTotalRepayAmountValue.text =
                            result.currency+ " " + result.repayAmount.toFirstNellFinanceFirstNellString()

                        //还款日期
                        mFirstNellFragmentFirstNellBinding.textRepayDueDateValue.text =
                            result.repayDate

                        //借款金额
                        mFirstNellFragmentFirstNellBinding.textRepayLoanAmountValue.text =
                            result.currency+ " " + result.amount.toFirstNellFinanceFirstNellString()

                        //利息
                        mFirstNellFragmentFirstNellBinding.textRepayInterestValue.text =
                            result.currency+ " " + result.interest.toFirstNellFinanceFirstNellString()

                        //服务费
                        mFirstNellFragmentFirstNellBinding.textRepayServiceFeeValue.text =
                            result.currency+ " " + (result.serviceFee
                                ?: "0").toFirstNellFinanceFirstNellString()

                        //服务费 vat
                        mFirstNellFragmentFirstNellBinding.textRepayServiceFeeVatValue.text =
                            result.currency+ " " + (result.serviceVatFee
                                ?: "0").toFirstNellFinanceFirstNellString()

                        //逾期
                        mFirstNellFragmentFirstNellBinding.textRepayOverdueDaysValue.text =
                            result.overdueDay.toString().toFirstNellDaysFirstNellSuffix()

                        //逾期利息
                        mFirstNellFragmentFirstNellBinding.textRepayOverduePenaltyValue.text =
                            result.currency+ " " + result.overdueAmount.toFirstNellFinanceFirstNellString()

                        //默认为全款还
                        mFirstNellFragmentFirstNellBinding.textRepayPaymentAmount.text =
                            result.repayAmount
                    }
                }
            }

            //获取还款链接回调
            mRepayViewModel.onFirstNellFetchFirstNellRepayFirstNellUrlFirstNellKSHFirstNellLiveData.observe(
                viewLifecycleOwner
            ) {
                mFirstNellFragmentFirstNellBinding.srlRepayPullRefresh.isRefreshing = false
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        try {
                            val repayUrl = result.repayUrl
                            val url = result.repayUrl
                            if (repayUrl?.isNotBlank() == true) {
                                mFirstNellFragmentFirstNellBinding.submitRepay.context.openFirstNellUrlFirstNellFromFirstNellSysFirstNellBrowser(
                                    repayUrl
                                )
                            } else {
                                mFirstNellFragmentFirstNellBinding.submitRepay.context.openFirstNellUrlFirstNellFromFirstNellSysFirstNellBrowser(
                                    url
                                )
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            }

            //查询用户状态回调
            mRepayViewModel.onFirstNellFetchFirstNellIsFirstNellRepayFirstNellNowFirstNellLiveData.observe(
                viewLifecycleOwner
            ) {
                mFirstNellFragmentFirstNellBinding.srlRepayPullRefresh.isRefreshing = false
                if (it.isSuccess) {
                    if (it.getOrNull() == true) {
                        //请求还款接口-加纳
                        mRepayViewModel.fetchFirstNellRepayFirstNellUrlFirstNellKSH(
                            ReqRepayUrl(deferredFlag = "NO")
                        )
                    } else {
                        (requireContext() as BaseActivity).startFirstNellToFirstNellNextFirstNellFromFirstNellPage(
                            PageTagEnum.repay
                        )
                    }
                }
            }

            //点击线上还款
            mFirstNellFragmentFirstNellBinding.submitRepay.setOnClickListener {
                mFirstNellFragmentFirstNellBinding.submitRepay.recordFirstNellClickFirstNellEvent()
                mRepayViewModel.fetchFirstNellIsFirstNellRepayFirstNellNow(
                    ReqBase()
                )
            }

            //点击展开全部还款
            mFirstNellFragmentFirstNellBinding.imageRepayBillDetailFullRepayExtend.setOnClickListener {
                mFirstNellFragmentFirstNellBinding.imageRepayBillDetailFullRepayExtend.recordFirstNellClickFirstNellEvent()
                showFirstNellFullFirstNellRepayFirstNellInfo()
            }

            //如果为科特，需要显示vat字段
            mFirstNellFragmentFirstNellBinding.rlRepayServiceFeeVatRow.visibility = View.GONE
            if (UsageCountryUtil.isFirstNellCountryFirstNellCotediva()) {
                mFirstNellFragmentFirstNellBinding.rlRepayServiceFeeVatRow.visibility = View.VISIBLE
            }

            //获取还款信息
            mRepayViewModel.fetchFirstNellRepayFirstNellDetail(ReqBase())

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /** 点击展示还款信息 */
    private fun showFirstNellFullFirstNellRepayFirstNellInfo() {
        if (mFirstNellFragmentFirstNellBinding.llRepayRepayBillDetail.visibility == View.GONE) {
            mFirstNellFragmentFirstNellBinding.llRepayRepayBillDetail.visibility =
                View.VISIBLE
            mFirstNellFragmentFirstNellBinding.imageRepayBillDetailFullRepayExtend.setImageResource(
                R.drawable.first_nell_repay_bill_close
            )
        } else {
            mFirstNellFragmentFirstNellBinding.llRepayRepayBillDetail.visibility =
                View.GONE
            mFirstNellFragmentFirstNellBinding.imageRepayBillDetailFullRepayExtend.setImageResource(
                R.drawable.first_nell_repay_bill_open
            )
        }
    }
}